<template>
  <div>
    <el-form :model="loginForm" @submit.prevent="login" :rules="loginRules" label-width="80px" class="login-form">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">登录</el-button>
        <el-button type="primary" @click="toRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

const loginForm = ref({
  username: '',
  password: ''
});

const loginRules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
});

const login = async () => {
  try {
    const result = await axios.post('/login', loginForm.value);
    if (result.data.code === 200) {
      ElMessage({
        message: '登录成功',
        type: 'success'
      });
      setTimeout(() => {
        //提示登录成功，并且把token存储到本地
        window.electron.ipcRenderer.send(
          'login-success',
          result.data.data.token,
          result.data.data.userId,
          result.data.data.name
        );
      }, 1000);
    }
  } catch (err: any) {
    ElMessage({
      message: `${err.response.data.msg}`,
      type: 'warning'
    });
  }
};

const toRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-form {
  width: 300px;
  margin: 0 auto;
  margin-top: 100px;
}
</style>
